import createjs.*
import kotlinx.browser.document
import org.w3c.dom.HTMLCanvasElement

import kotlin.random.Random

fun createRaindrops(stage: Stage) {
    val raindrops = mutableListOf<dynamic>()

    for (i in 0 until 100) {
        val raindrop: dynamic = Shape()
        raindrop.graphics.beginFill("#fff").drawRect(0, 0, 2, 10)
        raindrop.x = Random.nextDouble(0.0, stage.canvas.width.toDouble())
        raindrop.y = Random.nextDouble(0.0, stage.canvas.height.toDouble())
        raindrop.speed = Random.nextDouble(2.0, 10.0)

        stage.addChild(raindrop)
        raindrops.add(raindrop)
    }

    Ticker.addEventListener("tick", {
        for (raindrop in raindrops) {
            raindrop.y += raindrop.speed
            if (raindrop.y > stage.canvas.height) {
                raindrop.y = (-10).toDouble()
                raindrop.x = Random.nextDouble(0.0, stage.canvas.width.toDouble())
                raindrop.speed = Random.nextDouble(2.0, 10.0)
            }
        }
    })
}


fun main() {
    val el = document.createElement("canvas") as HTMLCanvasElement
    el.width = 800
    el.height = 600
    document.body?.appendChild(el)
    val stage = Stage(el)

    createRaindrops(stage)
    Ticker.framerate = 60
    Ticker.addEventListener(TickerEvent.TICK, { stage.update() })
}